//
//  BluetoothWeighingViewController.m
//  PPScaleDemo
//
//  Created by 彭思远 on 2021/3/11.
//

#import "BluetoothWeighingViewController.h"
#import "BodyDetailViewController.h"
#import "BodyDetailTool.h"


@interface BluetoothWeighingViewController ()<PPDataInterface, PPBleStateInterface>
@property (weak, nonatomic) IBOutlet UILabel *currentWeightLabel;
@property (weak, nonatomic) IBOutlet UILabel *connectStateLabel;
@property (nonatomic, strong) NSArray *userInfoArr;

@property (nonatomic, strong) PPScaleManager *scaleManager;
@property (nonatomic, strong) UserModel *currentUser;
@property (nonatomic, assign) BOOL isSelectUser;
@property (nonatomic, assign) PPUserUnit unit;

@end

@implementation BluetoothWeighingViewController


+ (instancetype)instance{
    return [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"BluetoothWeighingViewController"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Bluetooth weighing";
    [self newSearch];
    

    
    PPUserModel *userModel1 = [[PPUserModel alloc] initWithUserHeight:self.currentUser.userHeight gender:self.currentUser.userGender age:self.currentUser.userAge pregnantMode:self.currentUser.isPregnantMode athleteMode:self.currentUser.isAthleteMode andUnit:self.currentUser.userUnit];
    [userModel1 addUserId:@"1006451068@qq.com" memberId:@"A83C3D98-89C0-423A-A266-EFF74F7544B4" deviceHeaderIndex:0 userName:@"B4"];

    PPUserModel *userModel2 = [[PPUserModel alloc] initWithUserHeight:self.currentUser.userHeight gender:self.currentUser.userGender age:self.currentUser.userAge pregnantMode:self.currentUser.isPregnantMode athleteMode:self.currentUser.isAthleteMode andUnit:self.currentUser.userUnit];
    [userModel2 addUserId:@"1006451068@qq.com" memberId:@"A83C3D98-89C0-423A-A266-EFF74F7544B5" deviceHeaderIndex:1 userName:@"B5"];

    PPUserModel *userModel3 = [[PPUserModel alloc] initWithUserHeight:self.currentUser.userHeight gender:self.currentUser.userGender age:self.currentUser.userAge pregnantMode:self.currentUser.isPregnantMode athleteMode:self.currentUser.isAthleteMode andUnit:self.currentUser.userUnit];
    [userModel3 addUserId:@"1006451068@qq.com" memberId:@"A83C3D98-89C0-423A-A266-EFF74F7544B6" deviceHeaderIndex:2 userName:@"B6"];

    PPUserModel *userModel4 = [[PPUserModel alloc] initWithUserHeight:self.currentUser.userHeight gender:self.currentUser.userGender age:self.currentUser.userAge pregnantMode:self.currentUser.isPregnantMode athleteMode:self.currentUser.isAthleteMode andUnit:self.currentUser.userUnit];
    [userModel4 addUserId:@"1006451068@qq.com" memberId:@"A83C3D98-89C0-423A-A266-EFF74F7544B7" deviceHeaderIndex:3 userName:@"B7"];

    self.userInfoArr = @[userModel1, userModel2, userModel3, userModel4];
    [self.scaleManager torreSyncCurrentDeviceTimeWithSuccessHandler:^(BOOL isSuccess) {
        
    }];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.scaleManager disconnect];
}


- (void)newSearch{
    
    self.currentUser = [IdentityManager manager].currentUser;
    PPUserModel *userModel = [[PPUserModel alloc] initWithUserHeight:self.currentUser.userHeight gender:self.currentUser.userGender age:self.currentUser.userAge pregnantMode:self.currentUser.isPregnantMode athleteMode:self.currentUser.isAthleteMode andUnit:self.currentUser.userUnit];
    NSArray *deviceArr = [DeviceModel allObjects];
    NSMutableArray *macArr = @[].mutableCopy;
    for (DeviceModel *device in deviceArr) {
        [macArr addObject:device.deviceMac];
    }
    self.scaleManager = [[PPScaleManager alloc] initWithMacAddressList:macArr andUserModel:userModel];
    self.scaleManager.stateInterface = self;
    self.scaleManager.dataInterface = self;
    [self.scaleManager startSearching];
}

/// 监听秤发出的过程数据
- (void)scaleManager:(PPScaleManager *)manager monitorProcessData:(PPBodyBaseModel *)model{
    self.currentWeightLabel.text = [UnitTool weightStrWithDevice:manager.currentDevice weightKg:model.weight / 100.0 andUnitType:self.currentUser.userUnit];
    
    
    NSDictionary *dic = [PPUnitTool weightStrWithGFloat:model.weight accuracyType:manager.currentDevice.deviceAccuracyType andUnit:PPUnitFLOZWater];
    self.unit = model.unit;
    if (model.isEnd && !self.isSelectUser) {
        self.isSelectUser = YES;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.scaleManager torreSelectUser:self.userInfoArr.firstObject andSuccessHandler:^(BOOL isSuccess) {
                
            }];
            
        });

    }
}


- (IBAction)unitChangeBtnClick:(id)sender {
    [self.scaleManager caChangeUnit:self.unit];

}

- (void)scaleManager:(PPScaleManager *)manager monitorLockData:(PPBodyFatModel *)model {
    
    
    self.currentWeightLabel.text = [UnitTool weightStrWithDevice:manager.currentDevice weightKg:model.ppWeightKg andUnitType:self.currentUser.userUnit];
    if (model.ppIsHeartRateEnd) {
//        UINavigationController *nav = self.navigationController;
//        [nav popViewControllerAnimated:NO];
//        NSString * jsonString = [model mj_JSONString];
//        BodyDetailViewController *vc = [BodyDetailViewController instance];
//        vc.detailStr = [NSString stringWithFormat:@"%@", [jsonString stringByReplacingOccurrencesOfString:@"," withString:@"\n"]];
//        [nav pushViewController:vc animated:YES];
        
        
//        BodyDetailTool *tool = [[BodyDetailTool alloc] initWithPPBodyFatModel:model];
//        NSArray *bodyArr = [tool flagBodyArr];
//        NSArray *jsonArr = [BodyDetailModel mj_keyValuesArrayWithObjectArray:bodyArr];
//        NSString *jsonStr = [jsonArr mj_JSONString];
//        BodyDetailViewController *vc = [BodyDetailViewController instance];
//        vc.detailStr = jsonStr;
//        [nav pushViewController:vc animated:YES];
    }
}


- (void)monitorBluetoothWorkState:(PPBleWorkState)state{
    switch (state) {
        case PPBleWorkStateSearching:
            self.connectStateLabel.text = @"Scanning";
            break;
        case PPBleWorkStateSearchStop:
            self.connectStateLabel.text = @"Stop scanning";

            break;
        case PPBleWorkStateConnecting:
            self.connectStateLabel.text = @"Connecting";

            break;
        case PPBleWorkStateConnected:
            self.connectStateLabel.text = @"Connected";

            break;
        case PPBleWorkStateDisconnected:
            self.connectStateLabel.text = @"disconnected";
            [self.scaleManager reStartSearching];
            break;
        case PPBleWorkStateCouldReciveData:{
            [self.scaleManager syncSchema2Scale];
            if (self.scaleManager.currentDevice.deviceFuncType & PPDeviceFuncTypeHistory) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.scaleManager syncTime2Scale];

                });
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.scaleManager fetchHistoryData];

                });
            }

            [self.scaleManager caChangeTime:[NSDate date]];
            
            self.isSelectUser = NO;
            
            [self.scaleManager torreSyncAllUserInfo:self.userInfoArr andSuccessHandler:^(BOOL isSuccess) {
                NSLog(@"所有torre用户下发成功");
            }];
            
       
        }
            
            break;
        case PPBleWorkStateCouldStartOTA:
            
            break;
    }
}

- (void)monitorBluetoothSwitchState:(CBManagerState)state API_AVAILABLE(ios(10.0)){
    if (state != CBManagerStatePoweredOn) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Please turn on Bluetooth first" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
    }


}

- (void)monitorBluetoothAuthorState:(CBManagerAuthorization)state API_AVAILABLE(ios(13.0)){
    if (state != CBManagerAuthorizationAllowedAlways) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Please enable the Bluetooth permissions first" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}




@end
